from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.shortcuts import render, redirect

from tools.models import models
from django import forms

from tools.models.models import PrettyNum
from tools.utils.PageData import PageData
from tools.utils.modelform import BootStrapModelForm


# ######################## ModelForm 示例 ########################

# ============================== 新增用户 ==============================

# class UserModelForm(forms.ModelForm):
# init提出去放到modelform.py
class UserModelForm(BootStrapModelForm):

    # 添加一个最小长度校验
    name = forms.CharField(
        min_length=3,
        label="用户名"

    )
    # password = forms.CharField(validators=正则表达式, label="密码")

    class Meta:
        model = models.UserInfo
        fields = ["name", "password", "age", "account", "creatime", "gender", "depart"]
        # 逐一控制标签的样式
        # widgets = {
        #     "name": forms.TextInput(attrs={"class": "form-control"}),
        #     "password": forms.PasswordInput(attrs={"class": "form-control"})
        # }

        # 这里让日期可以手动点击鼠标选择,所以单独拎出来,加上日期插件
        widgets = {
            # "create_time": forms.DateInput(attrs={'class': 'form-control', 'id': 'myDate'}),
            "create_time": forms.DateInput(attrs={'id': 'myDate'}),
        }

    # # 用来替换上边的 widgets = {。。。}
    # # 添加bootstrap样式（提取到modelform.py里）
    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    #
    #     # 循环找到所有的字段插件，给所有的插件添加"class: form-control"属性
    #     # print(type(self.fields))  # 应该是 <class 'dict'>
    #     # print(self.fields)  # 检查内容
    #     for name,field in self.fields.items():
    #     # for name, field in dict(self.fields).items():
    #         print(name,field)
    #         field.widget.attrs = {"class": "form-control"}


# ============================== 新增靓号 ==============================

# class PrettynumForm(forms.ModelForm):
# init提出去放到modelform.py
class PrettynumForm(BootStrapModelForm):

    # 验证：方式一
    mobile = forms.CharField(
        label="手机号",
        # validators=[RegexValidator(r'^159[0-9]+$', '数字必须以159开头'),],
        # validators=[RegexValidator(r'^1\d{10}$', '手机号格式错误'),],
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误'),],
    )
    # mobile = forms.CharField(
    #     label=("手机号"),
    #     max_length=11,
    #     min_length=11,
    #     validators=[
    #         RegexValidator(
    #             r'^1[3456789]\d{9}$',  # 更精确的运营商号段
    #             message=("请输入正确的11位手机号")
    #         )
    #     ],
    #     widget=forms.TextInput(attrs={
    #         'placeholder': ('请输入手机号'),
    #         'pattern': '1[3456789]\\d{9}',  # HTML5 前端验证
    #         'title': ('请输入11位手机号')
    #     })
    # )

    class Meta:
        model = models.PrettyNum
        fields = ["mobile", "price", "level", "status"]
        # fields = "__all__"      # 全部字段
        # exclude = ['level']   # 排除某个字段
        # widgets = {
        #     "mobile": forms.TextInput(attrs={"class": "form-control"}),
        #     "price": forms.PasswordInput(attrs={"class": "form-control"})
        # }

    # # 添加bootstrap样式（提取到modelform.py里）
    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    #
    #     # 循环找到所有的字段插件，给所有的插件添加"class: form-control"属性
    #     # print(type(self.fields))  # 应该是 <class 'dict'>
    #     # print(self.fields)  # 检查内容
    #     for name,field in self.fields.items():
    #     # for name, field in dict(self.fields).items():
    #         print(name,field)
    #         field.widget.attrs = {"class": "form-control"}


    # 验证：方式二，钩子方法
    def clean_mobile(self):

        # 当前编辑的哪一行的ID
        print(self.instance.pk)

        txt_mobile = self.cleaned_data["mobile"]  # 获取用户输入/传入的数据

        if len(txt_mobile) != 11:
            # 验证不通过
            raise ValidationError("格式错误")

        # exclude(id=self.instance.pk) 排除自己
        # exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在！")

        # 验证通过
        return txt_mobile


# ============================== 编辑靓号 ==============================

# class PrettyEditModelForm(forms.ModelForm):
# init提出去放到modelform.py
class PrettyEditModelForm(BootStrapModelForm):

    # 加上手机号字段,但是不可编辑
    mobile = forms.CharField(disabled=True, label='手机号')

    # 数据校验: 验证方式1
    # mobile = forms.CharField(
    #     label="手机号",
    #     validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误'),],
    # )

    class Meta:
        model = models.PrettyNum
        # fields = "__all__"    表示取表中所有的字段
        fields = ['mobile', 'price', 'level', 'status']
        # exclude = ['level']   表示取除了表中的某个字段的所有字段

    # # 循环找到所有的插件,加入css样式,添加 "class": "form-control"（提取到modelform.py里）
    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    #
    #     for name, field in self.fields.items():
    #         print(name, field)
    #         field.widget.attrs = {"class": "form-control"}

    # 数据校验: 验证方式2
    def clean_mobile(self):
        txt_mobile = self.cleaned_data['mobile']

        if len(txt_mobile) != 11:
            # 验证不通过
            raise ValidationError('格式错误')

        # exclude 表示排除哪一个数据
        # self.instance.pk 表示当前编辑的哪一行 id
        exists_data = PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if exists_data:
            raise ValidationError("手机号已存在")

        # 验证通过
        return txt_mobile


# ============================== 任务管理 ==============================

class TaskModelForm(BootStrapModelForm):
    class Meta:                             # Django ModelForm 的配置类，用于指定表单的元数据
        model = models.Task                 # 指定这个表单关联的模型是 models.Task
        fields = '__all__'                  # 所有字段，也可以指定具体字段列表，如 fields = ['title', 'detail', 'level']
        widgets = {                         # 单独针对详细信息进行控件控制，用于覆盖字段的默认 widget（表单控件）
            'detail': forms.TextInput,      # detail 字段使用 TextInput（单行输入框）
            # 'detail': forms.Textarea,     # 注释掉的 Textarea 是多行文本框的替代方案
        }


class AddTaskModelForm(BootStrapModelForm):

    # # 验证：方式一
    # title = forms.CharField(
    #     label=("任务名称"),
    #     max_length=10,
    #     min_length=6,
    # )

    class Meta:
        model = models.Task
        fields = ["title", "detail", "level", "user"]
        # fields = "__all__"      # 全部字段
        # widgets = {
        #     "title": forms.TextInput(attrs={"class": "form-control"}),
        #     "detail": forms.TextInput(attrs={"class": "form-control"}),
        #     "level": forms.TextInput(attrs={"class": "form-control"}),
        #     "user": forms.TextInput(attrs={"class": "form-control"})
        # }

    # # 添加bootstrap样式（提取到modelform.py里）
    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    #
    #     # 循环找到所有的字段插件，给所有的插件添加"class: form-control"属性
    #     # print(type(self.fields))  # 应该是 <class 'dict'>
    #     # print(self.fields)  # 检查内容
    #     for name,field in self.fields.items():
    #     # for name, field in dict(self.fields).items():
    #         print(name,field)
    #         field.widget.attrs = {"class": "form-control"}

    # 数据校验: 验证方式2
    def clean_title(self):
        txt_title = self.cleaned_data['title']

        if len(txt_title) < 6:
            # 验证不通过
            raise ValidationError('格式错误')

        # exclude 表示排除哪一个数据
        # self.instance.pk 表示当前编辑的哪一行 id
        # exists_data = models.Task.objects.exclude(id=self.instance.pk).filter(mobile=txt_title).exists()
        exists_data = models.Task.objects.filter(title=txt_title).exists()
        print("exists_data",exists_data)
        if exists_data:
            raise ValidationError("任务已存在")

        # 验证通过
        return txt_title


class EditTaskModelForm(BootStrapModelForm):
    class Meta:
        model = models.Task
        fields = ["title", "detail", "level", "user"]


# ============================== 订单管理 ==============================

class OrderModelForm(BootStrapModelForm):
    class Meta:
        model = models.Order
        fields = "__all__"


class AddOrderModelForm(BootStrapModelForm):
    class Meta:
        model = models.Order
        fields = "__all__"

    def clean_oid(self):
        txt_oid = self.cleaned_data['oid']
        if len(txt_oid) < 6 or len(txt_oid) > 20:
            # 验证不通过
            raise ValidationError('格式错误:订单号长度需大于6小于12')
        # exclude 表示排除哪一个数据
        # self.instance.pk 表示当前编辑的哪一行 id
        # exists_data = models.Task.objects.exclude(id=self.instance.pk).filter(mobile=txt_title).exists()
        exists_data = models.Order.objects.filter(title=txt_oid).exists()
        print("exists_data",exists_data)
        if exists_data:
            raise ValidationError("订单已存在")
        # 验证通过
        return txt_oid


class EditOrderModelForm(BootStrapModelForm):
    # 订单号不可编辑
    oid = forms.CharField(disabled=True, label='订单号')
    class Meta:
        model = models.Order
        fields = "__all__"

    def clean_title(self):
        txt_title = self.cleaned_data['title']
        if len(txt_title) < 2:
            # 验证不通过
            raise ValidationError('格式错误:商品名称长度要大于1')
        # exclude 表示排除哪一个数据
        # self.instance.pk 表示当前编辑的哪一行 id
        # exists_data = models.Task.objects.exclude(id=self.instance.pk).filter(mobile=txt_title).exists()
        # exists_data = models.Order.objects.filter(title=txt_oid).exists()
        # print("exists_data",exists_data)
        # if exists_data:
        #     raise ValidationError("订单已存在")
        # # 验证通过
        return txt_title